import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import { message, Modal, notification } from 'ant-design-vue' /// es/notification
import { VueAxios } from './axios'
import { ACCESS_TOKEN } from '@/store/mutation-types'

// 获取baseURL
function getUrlFromBrowser() {
  const protocol = window.location.protocol
  const urlFamily = window.location.host.split(':')
  const hostname = urlFamily[0] // "192.168.0.20";
  let urlPort = urlFamily.length === 2 ? Number(urlFamily[1]) : null
  if (urlPort === 81) {
    urlPort = 9001
  }

  return `${protocol}//${hostname}${urlPort ? ':' + urlPort : ''}${urlPort !== 9001 ? '/api' : ''}`
}

// 创建 axios 实例
const service = axios.create({
  baseURL: getUrlFromBrowser() // api base_url
  // timeout: 20000 // 请求超时时间
})

// 异常处理
const err = (error) => {
  if (error.response) {
    const data = error.response.data
    const token = Vue.ls.get(ACCESS_TOKEN)

    if (error.response.status === 403) {
      notification.error({
        message: 'Forbidden',
        description: data.message
      })
    }
    if (error.response.status === 500) {
      if (data.error.length > 0) {
        message.error(data.message)
      }
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      notification.error({
        message: 'Unauthorized',
        description: 'Authorization verification failed'
      })
      if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }
    }
  }
  return Promise.reject(error)
}

// 请求拦截器
service.interceptors.request.use(request => {
  const token = Vue.ls.get(ACCESS_TOKEN)
  if (token) {
    request.headers['Authorization'] = 'JWT' + ' ' + token
    request.timeout = request.timeout || 30000
  }
  return request
})


// response处理
function handleResponse(response) {
  let result
  if (response.status === 401) {
    result = '会话过期，请重新登录'
    if (history.location.pathname !== '/') {
      history.push('/', { from: history.location })
    } else {
      return Promise.reject()
    }
  } else if (response.status === 200) {
    if (response.data.error) {
      result = response.data.error
    } else if (response.data.hasOwnProperty('data')) {
      return Promise.resolve(response.data.data)
    } else if (response.headers['content-type'] === 'application/octet-stream') {
      return Promise.resolve(response)
    } else if (!response.config.isInternal) {
      return Promise.resolve(response.data)
    } else {
      result = '无效的数据格式'
    }
  } else {
    result = `请求失败: ${response.status} ${response.statusText}`
  }
  message.error(result)
  return Promise.reject(result)
}

/**
 * response interceptor
 */
service.interceptors.response.use((response) => {
  const code = response.data.code
  if (code === 1011006 || code === 1011007 || code === 1011008 || code === 1011009 || code === 401) {
    console.log('response interceptor')
    Modal.error({
      title: '提示：',
      content: response.data.message || '认证已过期',
      okText: '重新登录',
      onOk: () => {
        Vue.ls.remove(ACCESS_TOKEN)
        window.location.reload()
      }
    })
  } else if (code === 4000) {
    message.error(response.data.message)
    return response.data
  } else {
    return response.data
  }
}, err)

const installer = {
  vm: {},
  install(Vue) {
    Vue.use(VueAxios, service)
  }
}

export {
  installer as VueAxios,
  service as axios
}
